package com.enation.app.javashop.consumer.shop.goodssearch;

import com.enation.app.javashop.consumer.core.event.GoodsIndexInitEvent;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.client.goods.GoodsIndexClient;
import com.enation.app.javashop.core.system.progress.model.ProgressEnum;
import com.enation.app.javashop.core.system.progress.model.TaskProgress;
import com.enation.app.javashop.core.system.progress.model.TaskProgressConstant;
import com.enation.app.javashop.core.system.progress.service.ProgressManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author fk
 * @version v1.0
 * @Description: 商品索引初始化
 * @date 2018/6/25 11:38
 * @since v7.0.0
 */
@Service
public class GoodsIndexInitConsumer implements GoodsIndexInitEvent {

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private ProgressManager progressManager;
    @Autowired
    private GoodsIndexClient goodsIndexClient;
    @Autowired
    private GoodsClient goodsClient;

    @Override
    public void createGoodsIndex() {

        try {
            String key = TaskProgressConstant.GOODS_INDEX;

            /** 获取商品数 */
            int goodsCount = this.goodsClient.queryGoodsCount();
            /** 生成任务进度 */
            TaskProgress taskProgress = new TaskProgress(goodsCount);
            progressManager.putProgress(key, taskProgress);
            int pageSize = 100;
            int pageCount;
            pageCount = goodsCount / pageSize;
            pageCount = goodsCount % pageSize > 0 ? pageCount + 1 : pageCount;
            for (int i = 1; i <= pageCount; i++) {

                List<Map> goodsList = this.goodsClient.queryGoodsByRange(i,pageSize);
                Integer[] goodsIds = new Integer[goodsList.size()];
                int j = 0;
                for (Map map : goodsList) {
                    goodsIds[j] = Integer.valueOf(map.get("goods_id").toString());
                    j++;
                }

                List<Map<String, Object>> list = goodsClient.getGoodsAndParams(goodsIds);

                goodsIndexClient.addAll(list, i);

            }
            TaskProgress task = progressManager.getProgress(key);
            task.step("索引生成完成");
            task.success();
            /** 更新进度 重新放入缓存 */
            progressManager.putProgress(key, task);
        } catch (Exception e) {
            TaskProgress tk = progressManager.getProgress(TaskProgressConstant.GOODS_INDEX);
            tk.setTaskStatus(ProgressEnum.EXCEPTION.name());
            tk.setMessage("生成所索引异常，请联系运维人员");
            progressManager.putProgress(TaskProgressConstant.GOODS_INDEX, tk);
            this.logger.error("生成索引异常：", e);
        }

    }

}
